﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Configuration;
using System.Data;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        [HttpPost]
        public ActionResult Index(string searchtext)
        {
            //return RedirectToAction("Search",new{searchtext=searchtext});
            return RedirectToRoute("Query", new { searchtext = searchtext });
        }

        [HttpGet]
        public ActionResult Search(string searchtext,int? page)
        {
            if (searchtext == "") return View("Index");
            //string sqlconnstr = ConfigurationManager.ConnectionStrings["cj"].ConnectionString;
            //DataToSearch dts = new DataToSearch(sqlconnstr);
            DataView searchresult;
            //if (dts.Init() == true)
            //{
            Searcher searcher = new Searcher(HttpContext.Application["datatosearch"] as DataToSearch);
            List<string> keywords = new List<string>();
            foreach (string substr in searchtext.Split(' '))
            {
                keywords.Add(substr);
            }
            searchresult = searcher.search(keywords);
            int pagenumber = page ?? 1;
            Pager<DataView> pager = new DataViewPager(searchresult, pagenumber, 12);
            ViewBag.dataview = pager.CurrentPage;
            ViewBag.searchtext = searchtext;
            //return View();
            //}
            Request.ContentEncoding = new System.Text.UTF8Encoding();
            return View();
        }

        [HttpPost]
        public ActionResult Search(string searchtext)
        {
            return RedirectToRoute("Query", new { searchtext = searchtext });
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
